package com.czk.netty.netty.rpc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/30 14:26
 */
public class NettyServer {
    public static void startServer(String hostName, int port) {
        startServer0(hostName, port);
    }

    /**
     * 启动nettyServer的方法
     *
     * @param hostName
     * @param port
     */
    public static void startServer0(String hostName, int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel socketChannel) throws Exception {
                                    // 拿到管道
                                    ChannelPipeline pipeline = socketChannel.pipeline();
                                    // 加入编解码器
                                    pipeline.addLast(new StringDecoder());
                                    pipeline.addLast(new StringEncoder());
                                    // 加入自己的业务处理器
                                    pipeline.addLast(new NettyServerHandler());
                                }
                            }
                    );
            // 绑定端口
            ChannelFuture sync = bootstrap.bind(hostName, port).sync();
            sync.channel().closeFuture().sync();
        } catch (Exception ex) {

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
